/**
 * Project Name:dubbox-demo
 * File Name:Consumer
 * Package Name:com.fft.dubbox.consumer
 * Date:2016/6/2116:06
 * Copyright (c) 2016,  www.shfft.com All Rights Reserved.
 */
package com.fft.dubbox.consumer;

import com.fft.dubbox.servicce.UserService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;

/**
 * ClassName: Consumer
 * Reason: dubbox消费者.
 * date: 2016/6/21 16:06
 *
 * @author libin
 * @since JDK 1.6
 */
public class Consumer {

    public static void main(String[] args) {
        final String port = "8888";
        //测试Rest服务
        getUser("http://localhost:" + port + "/services/users/1.json");
        getUser("http://localhost:" + port + "/services/users/2.xml");

        //测试常规服务
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:dubbox/dubbox-consumer.xml");
        context.start();
        UserService userService = context.getBean(UserService.class);
        System.out.println("常规dubbox服务结果:"+userService.getUser(1L));
    }

    private static void getUser(String url) {
        System.out.println("Getting user via " + url);
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(url);
        Response response = target.request().get();
        try {
            if (response.getStatus() != 200) {
                throw new RuntimeException("Failed with HTTP error code : " + response.getStatus());
            }
            System.out.println("Successfully got result: " + response.readEntity(String.class));
        } finally {
            response.close();
            client.close();
        }
    }

}
